import {createStore as _createStore, applyMiddleware, compose} from 'redux';
import thunkMiddleware from 'redux-thunk';
import {matchRoutes} from 'react-router-config';

import utils from '../utils';
import routes from '../routes';
import rootReducer from './reducers';
// import {GET_PAGE_LEAVE_TO} from '../constants/actionTypes';

// function preloadMiddleware({dispatch, getState}) {
//     return next => action => {
//         const store = getState();
//         const {type, srcPath, reducerKey} = action;

//         if (type === GET_PAGE_LEAVE_TO) {

//             if (reducerKey) {
//                 let state = store[reducerKey];

//                 store[reducerKey] = {...state, loadover: false};
//             }
//             else {
//                 const branches = matchRoutes(routes, srcPath);

//                 branches.forEach(({route, match}, index) => {
//                     if (match.isExact && route.reducerKey) {
//                         let state = store[route.reducerKey];

//                         store[route.reducerKey] = {...state, loadover: false};
//                     }
//                 });
//             }
//         }

//         return next(action);
//     };
// }

function callTraceMiddleware({getState}) {
    return next => action => {
        if (utils.isBrowser()) {
            // const store = getState();

            let header = utils.getHTMLTitle(window.location.pathname, getState());

            utils.resetAPPHeader(header);
        }

        return next(action);
    };
}

export default function createStore(initState, extraArgs, composeEnhancers = compose) {
    const store = _createStore(
        rootReducer,
        initState,
        composeEnhancers(
            applyMiddleware(
                // preloadMiddleware,
                callTraceMiddleware,
                thunkMiddleware.withExtraArgument(extraArgs)
            )
        )
    );

    /* eslint-disable */
    if (module.hot) {
        // Enable Webpack hot module replacement for reducers
        module.hot.accept('./reducers', () => {
            const nextRootReducer = require('./reducers').default;
            store.replaceReducer(nextRootReducer);
        });
    }
    /* eslint-enable */

    return store;
}
